package com.atguigu.java;

import java.util.Arrays;

/**
 * @author azzn1400820029
 * @create 2021-12-12 17:39
 */

/*
 * 算法的考查：数组的复制、反转、查找(线性查找、二分法查找)
 *
 *
 */
public class ArrayTest2 {
    public static void main(String[] args) {
        String[] arr = new String[]{"JJ", "DD", "MM", "BB", "GG", "AA"};

//        数组的复制
        String[] arr1 = new String[arr.length];
        for (int i = 0; i < arr.length; i++) {
            arr1[i] = arr[i];
        }
        System.out.println(Arrays.toString(arr1));

//        数组的反转
//        方法一
        String[] arr2 = new String[arr.length];
        for (int i = 0; i < arr.length; i++) {
            arr2[i] = arr[arr.length - i - 1];
        }
        System.out.println(Arrays.toString(arr2));
//        方法二 注意判定条件
        for (int i = 0; i < arr.length / 2; i++) {
            String temp = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = arr[i];
            arr[i] = temp;
        }
        System.out.println("method2" + Arrays.toString(arr));
//      方法三 注意判定条件
        for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
            String temp = arr[j];
            arr[j] = arr[i];
            arr[i] = temp;
        }
        System.out.println("method3" + Arrays.toString(arr));

//        线性查找
        String dest = "BB";
        dest = "CC";

        boolean isflag = true;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equals(dest)) {
                System.out.println("找到了指定的元素，位置是：" + i);
                isflag = false;
                break;
            }
        }
        if (isflag) {
            System.out.println("没有找到");
        }

        //    二分法查找 前提数组是升序或者降序数组
        int[] arr3 = new int[]{-98, -34, 2, 34, 54, 66, 79, 105, 210, 333};
        int dest1 = -34;
//        dest1 = 35;

        int head = 0, end = arr2.length - 1;
        boolean isFlag1 = true;
        while (head <= end) {
            int middle = (head + end) / 2;
            if (dest1 == arr3[middle]) {
                System.out.println("找到了指定元素，位置是：" + middle);
                isFlag1 = false;
                break;
            } else if (arr3[middle] > dest1){
                end = middle - 1;
            } else {
                head = middle + 1;
            }
        }
        if (isFlag1) {
            System.out.println("很遗憾，没有找到");
        }
    }

}
